import { useCallback } from 'react'
import { Alert } from 'react-native'
import { getFilePresignedUrl, createFile, uploadFileToPresignedUrl, uploadFileDirectly, FilePresignedUrlRespVO } from '../api/file'

export interface UploadFile {
    uri: string
    type: string
    name: string
    size: number
}

export const useUpload = (directory?: string) => {
    // 生成文件名
    const generateFileName = useCallback((file: UploadFile) => {
        // 简单使用原文件名，也可以加上时间戳避免重复
        const timestamp = Date.now()
        const ext = file.name.substring(file.name.lastIndexOf('.'))
        const baseName = file.name.substring(0, file.name.lastIndexOf('.'))
        return `${timestamp}_${baseName.replace(/[^a-zA-Z0-9]/g, '_')}${ext}`
    }, [])

    // 创建文件记录
    const createFileRecord = useCallback(async (vo: FilePresignedUrlRespVO, file: UploadFile) => {
        const fileVo = {
            configId: vo.configId,
            url: vo.url,
            path: vo.path,
            name: file.name,
            type: file.type,
            size: file.size
        }

        try {
            await createFile(fileVo)
            return fileVo
        } catch (error) {
            console.error('创建文件记录失败:', error)
            throw error
        }
    }, [])

    // 上传单个文件
    const uploadFile = useCallback(async (file: UploadFile): Promise<string> => {
        try {
            // 1. 生成文件名
            const fileName = generateFileName(file)

            // // 2. 获取预签名URL
            // console.log('获取预签名URL...', fileName, directory)
            // const presignedResponse = await getFilePresignedUrl(fileName, directory)
            //
            // if (!presignedResponse.data) {
            //     throw new Error('获取预签名URL失败')
            // }
            //
            // const presignedData = presignedResponse.data
            // console.log('预签名URL获取成功:', presignedData)

            const directUploadResponse = await uploadFileDirectly({
                uri: file.uri,
                type: file.type,
                name: fileName,
                size: file.size
            }, directory)

            if (directUploadResponse.data) {
                return directUploadResponse.data
            } else {
                throw new Error('直接上传失败')
            }

            // try {
            //     // 3. 尝试上传文件到预签名URL
            //     console.log('开始上传文件到预签名URL...')
            //     await uploadFileToPresignedUrl(presignedData.uploadUrl, {
            //         uri: file.uri,
            //         type: file.type,
            //         name: fileName
            //     })

            //     console.log('文件上传成功')

            //     // 4. 创建文件记录
            //     console.log('创建文件记录...')
            //     await createFileRecord(presignedData, file)

            //     console.log('文件上传完成，返回URL:', presignedData.url)

            //     // 5. 返回文件URL
            //     return presignedData.url
            // } catch (uploadError) {
            //     console.warn('预签名URL上传失败，尝试直接上传到后端:', uploadError)

            //     // 备用方案：直接上传到后端
            //     console.log('使用直接上传方案...')
            //     const directUploadResponse = await uploadFileDirectly({
            //         uri: file.uri,
            //         type: file.type,
            //         name: fileName
            //     }, directory)

            //     if (directUploadResponse.data) {
            //         console.log('直接上传成功，返回URL:', directUploadResponse.data)
            //         return directUploadResponse.data
            //     } else {
            //         throw new Error('直接上传失败')
            //     }
            // }

        } catch (error) {
            console.error('文件上传失败:', error)
            Alert.alert('上传失败', error instanceof Error ? error.message : '文件上传过程中发生错误')
            throw error
        }
    }, [generateFileName, directory, createFileRecord])

    // 批量上传文件
    const uploadFiles = useCallback(async (files: UploadFile[]): Promise<string[]> => {
        const uploadPromises = files.map(file => uploadFile(file))

        try {
            const results = await Promise.all(uploadPromises)
            return results
        } catch (error) {
            console.error('批量上传失败:', error)
            throw error
        }
    }, [uploadFile])

    return {
        uploadFile,
        uploadFiles
    }
}